package com.xuecheng.learning.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.learning.config.PayNotifyConfig;
import com.xuecheng.learning.mapper.XcChooseCourseMapper;
import com.xuecheng.learning.model.po.XcChooseCourse;
import com.xuecheng.learning.model.po.XcCourseTables;
import com.xuecheng.learning.service.MyCourseTablesService;
import com.xuecheng.messagesdk.model.po.MqMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @version 1.0
 * @description 接收支付结果通知service
 * @Author Endeavor-ZQB
 * @Create 2023/2/22 11:06
 */
@Slf4j
@Service
public class ReceivePayNotifyService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    XcChooseCourseMapper chooseCourseMapper;

    @Autowired
    MyCourseTablesService myCourseTablesService;

    //接收支付结果通知
    @RabbitListener(queues = PayNotifyConfig.CHOOSECOURSE_PAYNOTIFY_QUEUE)
    public void receive(String message){
        //获取消息
        MqMessage mqMessage = JSON.parseObject(message, MqMessage.class);
        log.debug("学习中心服务接收支付结果:{}",mqMessage);

        //判断该消息是否是自己的消息
        String messageType = mqMessage.getMessageType();
        //订单业务类型
        String businessKey2 = mqMessage.getBusinessKey2();
        //只处理支付结果通知的消息并且是学生购买课程订单的消息
        if (PayNotifyConfig.MESSAGE_TYPE.equals(messageType) && "60201".equals(businessKey2)){
            //根据选课id查询选课记录
            String chooseCourseId = mqMessage.getBusinessKey1();
            XcChooseCourse chooseCourse = chooseCourseMapper.selectById(chooseCourseId);
            if (chooseCourse == null){
                log.info("收到支付结果通知，查询不到选课记录，chooseCourseId:{}",chooseCourseId);
            }
            //更新选课状态
            XcChooseCourse chooseCourse_u = new XcChooseCourse();
            chooseCourse_u.setStatus("701001");//选课成功
            LambdaQueryWrapper<XcChooseCourse> queryWrapper = new LambdaQueryWrapper<XcChooseCourse>().eq(XcChooseCourse::getId, chooseCourseId);
            chooseCourseMapper.update(chooseCourse_u,queryWrapper);

            //查询最新的课程记录
            chooseCourse = chooseCourseMapper.selectById(chooseCourseId);
            //添加到我的课程表中
            XcCourseTables courseTables = myCourseTablesService.addCourseTables(chooseCourse);

            //向订单服务回复消息
            send(mqMessage);



        }
    }
    
    /**
     * @Description 回复消息
     * @Param [mqMessage] 回复消息
     * @return void
     */
    public void send(MqMessage mqMessage){
        //转Json
        String msg = JSON.toJSONString(mqMessage);
        //发送消息
        rabbitTemplate.convertAndSend(PayNotifyConfig.PAYNOTIFY_REPLY_QUEUE,msg);
        
        log.info("学习中心服务向订单服务回复消息:{}",mqMessage);
    }
}
